<template>
<div :class="appDetail.theme?appDetail.theme:'defaultTheme'" class="applicationContainer">
    <div class="application main-view">
        <div class="app-header">
            <div class="header-top">
                <div class="header-top-left">
                    <a-tooltip placement="bottom">
                        <template slot="title" v-if="entryType==='self'">
                            <span>返回主页</span>
                        </template>
                        <div class="menu_button" @click.stop="handlePushBackClick">
                            <a-icon type="appstore" style="margin:0 10px 0 20px; font-size: 20px"/>
                        </div>
                    </a-tooltip>
                    <a-divider type="vertical" />
                    <a-tooltip placement="bottom" v-if="appAuths.auth.MANAGE_APP_AUTH">
                        <template slot="title">
                            <span>更换主题及图标</span>
                        </template>
                        <div class="menu_button" @click.stop="handleCommand('theme')">
                            主题
                        </div>
                    </a-tooltip>
                    <a-tooltip placement="bottom" v-if="appAuths.auth.MANAGE_APP_AUTH">
                        <template slot="title">
                            <span>API开发文档</span>
                        </template>
                        <div class="menu_button" @click.stop="handleCommand('apiDoc')">
                            API
                        </div>
                    </a-tooltip>
                </div>
                <div class="header-top-middle">
                    <span class="header-title" :title="appDetail.title">
                        <span style="font-size: 1.3rem" :class="[logoIconFontFamily, appDetail.icon?logoIconProfix+appDetail.icon:logoIconProfix+appDefaultIcon]"/>
                        {{appDetail.title}}
                    </span>
                    <a-icon type="caret-down" style="color: #ffffffcc; fontSize: 14px"/>
                </div>
                <div class="header-top-right">
                    <div class="header-top-help">
                        帮助
                        <a-icon type="question" />
                    </div>
                    <div class="menu_button" @click="handleNoticeClick">
                        <a-badge :count="count" :number-style="{
                            height: '10px',
                            lineHeight: '10px',
                            padding: 0,
                            minWidth: '10px'
                        }">
                            <a-icon type="bell" />
                        </a-badge>
                    </div>
                    <div class="menu_button">
                        <a-icon type="history" />
                    </div>
                    <div class="menu_button">
                        <a-icon type="user" style="font-size: 20px"/>
                    </div>
                </div>
            </div>
            <div class="header-bottom">
                <div class="menu_button" style="margin-left: 5px;" @click.stop="$store.commit('updateTableMenuExtend')">
                    <a-icon v-show="tableMenuExtend" type="menu-fold" />
                    <a-icon v-show="!tableMenuExtend" type="menu-unfold" />
                </div>
                <vuedraggable v-model="appDetail.worksheetGroupList">
                    <transition-group  class="header-bottom-middle">
                        <router-link class="header-menu-item flex-row" active-class="menu-group-active"
                            v-for="group in appDetail.worksheetGroupList"
                            :key="group.id"
                            :to="`/app/${appId}/${group.id}/${worksheetId}`"
                        >
                            <div style="margin: 0 auto;">
                                {{group.name}}
                                <el-dropdown
                                    v-if="checkEditAuth()"
                                    placement="bottom"
                                    @command="handleGroupCommand">
                                    <span class="el-dropdown-link" style="color: #00000080;">
                                        <a-icon type="caret-down" v-if="groupId === group.id"/>
                                    </span>
                                    
                                    <el-dropdown-menu slot="dropdown" >
                                        <el-dropdown-item icon="el-icon-edit" command="rename">重命名</el-dropdown-item>
                                        <el-dropdown-item icon="el-icon-plus" command="add">添加分组</el-dropdown-item>
                                        <el-dropdown-item v-show="appDetail.worksheetGroupList.length > 1" icon="el-icon-delete" command="delete" style="color: red;">
                                            删除分组
                                        </el-dropdown-item>
                                        
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                        </router-link>
                    </transition-group>
                </vuedraggable>
                <!-- <div v-if="appAuths.auth.MANAGE_APP_AUTH" class="menu_button" @click="$router.push(`/app/${appId}/workflow`)" style="position: absolute; right: 100px; width: 100px">
                    <a-icon type="fork" />
                    工作流
                </div> -->
                <div v-if="appAuths.auth.MANAGE_APP_AUTH" class="menu_button" style="position: absolute; right: 100px; width: 100px">
                    <a-icon type="fork" />
                    工作流
                </div>
                <div v-if="appAuths.auth.MANAGE_APP_AUTH" class="menu_button" style="position: absolute; right: 8px; min-width: 100px">
                    <a-icon type="profile" />
                    我的流程
                    <span v-if="msg_tip!=0">{{msg_tip}}</span>
                </div>
                <!-- <div v-if="appAuths.auth.MANAGE_APP_AUTH" class="menu_button" @click="$router.push('/my_flow')" style="position: absolute; right: 8px; min-width: 100px">
                    <a-icon type="profile" />
                    我的流程
                    <span v-if="msg_tip!=0">{{msg_tip}}</span>
                </div> -->
            </div>
        </div>
        <router-view></router-view>
        
        <el-dialog
            :title="dialogData.title"
            :visible.sync="dialogData.visible"
            width="30%"
            @close="dialogData.visible = false">
            <el-form ref="appForm"
                :model="formData"
                :rules="rules" 
                label-width="80px"
            >
                <el-form-item label="名称" prop="name">
                    <el-input v-model="formData.name"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleOK">确定</el-button>
                    <el-button @click="dialogData.visible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <delete-group v-if="deleteGroupVisible"
            :visible="deleteGroupVisible"
            @ok="handleDeleteGroupOk"
            @cancel="deleteGroupVisible = false"
        />
    </div>
    <notice-drawer-vue v-if="noticeDrawerVisible" :visible="noticeDrawerVisible" @close="noticeDrawerVisible = false"></notice-drawer-vue>
    <select-theme-icon v-if="selectThemeModalVisible" :themeClassName="appDetail.theme?appDetail.theme:'defaultTheme'" :iconName="appDetail.icon?appDetail.icon:appDefaultIcon" @changeTheme="changeTheme" @changeIcon="changeIcon" @close="closeThemeModal"></select-theme-icon>
</div>
</template>
<script>
    import {
        getAppDetail,
        addWorksheetGroup,
        updateWorksheetGroup,
        deleteWorksheetGroup,
        updateGroupSort,
        updateApp,
        getAppAuthV2,
        getNoticeCount,
        getTaskCount
    } from "@/api/app"
    import { getUserAuthority} from "@/util/auth";
    import vuedraggable from 'vuedraggable';

    import selectThemeIcon from "./selectThemeIcon.vue"
    import deleteGroup from "./modal/deleteGroup.vue"
    import { profix, font_family, defaultIcon_app } from "@/util/LOGO_ICON_CONFIG"
    import { getEntry } from "@/util/auth"
    import NoticeDrawerVue from "./drawer/noticeDrawer.vue";
    export default {
        name: "tenant",
        components:{
            vuedraggable,
            deleteGroup,
            selectThemeIcon,
            NoticeDrawerVue,
        },
        data () {
            return {
                themeClassName: 'defaultTheme',
                appDefaultIcon: defaultIcon_app,
                logoIconFontFamily: font_family,
                logoIconProfix: profix,
                selectThemeModalVisible: false,
                deleteGroupVisible: false,
                userInfo: {},
                tenantInfo: {},
                userRole: "",
                userAuthority: {},
                entryType: 'self',
                tenantId: '',
                appDetail: {
                    title: '未命名',
                    worksheetGroupList: []
                },
                dialogData: {
                    title: '新建工作表',
                    visible: false
                },
                dialogVisible: false,
                formData: {
                    name: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入工作表名称', trigger: 'blur' }
                    ]
                },
                noticeCount: [],
                noticeDrawerVisible: false,
                msg_tip: 0
            }
        },
        async created () {       
            // let data = await getTaskCount()
            // this.msg_tip = data[1]
            let userInfo = getUserAuthority();
            this.$store.commit('updateUserInfo', userInfo)

            let userAuth = await getAppAuthV2(this.appId);
            let authArray = userAuth.formAuth
            let auths = {
                appAuth:{},
                formAuth:{},
                isFormAuth: !!(userAuth.formAuth) && !(JSON.stringify(userAuth.formAuth) === "{}")
            }
            userAuth.appAuth.forEach(auth => auths.appAuth[auth] = true)
            if(auths.formAuth){
                for (const key in authArray) {
                    let element = authArray[key];
                    auths.formAuth[key] = {}
                    element.forEach(e => {
                        auths.formAuth[key][e] = true
                    })
                }
            }
            this.$store.commit('updateAppAuths', auths)

            let entry = getEntry()
            this.entryType = typeof(entry)==='object' && 'type' in entry ? entry.type : 'self'
            this.appDetail = await getAppDetail(this.appId)

            let noticeCount = await getNoticeCount()
            this.noticeCount = noticeCount
            // this.$store.commit('updateSysTheme', theme)
            if(this.$route.path.endsWith('workflow') && !this.groupId) return
            if(!this.groupId){
                let groupId = this.appDetail.worksheetGroupList[0]?.id || null
                this.$router.push(`/app/${this.appId}/${groupId}`)
            }

            this.$ws.on('send_notice', async (data) => {
                let noticeCount = await getNoticeCount()
                this.noticeCount = noticeCount
            })
            this.$ws.on('clear_notice', async (data) => {
                let noticeCount = await getNoticeCount()
                this.noticeCount = noticeCount
            })
        },
        methods: {
            handleNoticeClick(){
                this.noticeDrawerVisible = true
            },
            checkEditAuth(){
                let flag = false
                let {isFormAuth, auth} = this.appAuths
                if(isFormAuth){
                    if(auth.FORM_ADD){
                        flag = true
                    }
                }else{
                    if(auth.EDIT_FORM || auth.EDIT_FORM2 || auth.EDIT_FORM3){
                        flag = true
                    }
                }
                return flag
            },
            async handleDeleteGroupOk(data){
                this.deleteGroupVisible = false
                let {newGroupId} = data
                await deleteWorksheetGroup({
                    id: this.groupId,
                    newGroupId
                })
                this.dialogData.visible = false
                this.appDetail = await getAppDetail(this.appId)
                let groupId = this.appDetail.worksheetGroupList[0]?.id || null
                this.$router.push(`/app/${this.appId}/${groupId}/null`)
            },
            handlePushBackClick(){
                if(this.entryType !== 'self') return
                this.$router.push({
                    path: '/menu/App'
                })
            },
            closeThemeModal(){
                this.selectThemeModalVisible = false
            },
            async changeTheme(theme){
                let result = await updateApp({
                    "id": this.appId,
                    "theme": theme.className
                })
                if(result){
                    this.appDetail.theme = theme.className
                    this.$message.success('更新主题颜色成功！')
                } else {
                    this.$message.error('更新主题颜色失败！')
                }
                
            },
            async changeIcon(icon){
                let result = await updateApp({
                    "id": this.appId,
                    "icon": icon.iconName
                })
                if(result){
                    this.appDetail.icon = icon.iconName
                    this.$message.success('更新图标成功！')
                } else {
                    this.$message.error('更新图标失败！')
                }
                
            },
            handleCommand(command){
                if(command === 'apiDoc'){
                    let routeData = this.$router.resolve({
                        name: 'WorksheetApi',
                        params: { id: this.appId }
                    })
                    window.open(routeData.href, '_blank')
                } else if(command === 'theme') {
                    this.selectThemeModalVisible = true
                }
            },
            handleOK(){
                this.$refs['appForm'].validate(async (valid) => {
                    if (valid) {
                        if(this.dialogData.title === "新建分组") {
                            let data = await addWorksheetGroup({
                                name: this.formData.name,
                                appId: this.appId
                            })
                            this.dialogData.visible = false
                            this.appDetail = await getAppDetail(this.appId)
                            this.$router.push(`/app/${this.appId}/${data.id}/null`)
                        } else if (this.dialogData.title === "重命名") {
                            await updateWorksheetGroup({
                                name: this.formData.name,
                                id: this.groupId
                            })
                            this.dialogData.visible = false
                            this.appDetail = await getAppDetail(this.appId)
                        }
                    } else {
                        return false;
                    }
                });
            },
            handleGroupCommand(command) {
                if(command === 'rename'){
                    this.dialogData = {
                        title: '重命名',
                        visible: true
                    }
                } else if(command === 'add') {
                    this.dialogData = {
                        title: '新建分组',
                        visible: true
                    }
                } else if(command === 'delete') {
                    this.deleteGroupVisible = true
                    // this.$confirm("此操作将永久删除分组, 是否继续?", "提示", {
                    //     confirmButtonText: "确定",
                    //     cancelButtonText: "取消",
                    //     type: "warning"
                    // })
                    // .then(async () => {
                        // await deleteWorksheetGroup({
                        //     id: this.groupId
                        // })
                        // this.dialogData.visible = false
                        // this.appDetail = await getAppDetail(this.appId)
                        // let groupId = this.appDetail.worksheetGroupList[0]?.id || null
                        // this.$router.push(`/app/${this.appId}/${groupId}/null`)
                    // })
                    // .catch(() => {
                    //     this.$message({
                    //         type: "info",
                    //         message: "删除失败"
                    //     });
                    // });
                }
            }
        },
        watch:{
            async 'appDetail.worksheetGroupList' () {
                let worksheetGroupIds = this.appDetail.worksheetGroupList.map(l => l.id)
                await updateGroupSort({
                    "id": this.appId,
                    worksheetGroupIds,
                })
            },
            $route(to, from) {
                if(to.name !== from.name && to.name === 'appTableId'){
                    this.$ws.on('send_notice', async (data) => {
                        let noticeCount = await getNoticeCount()
                        this.noticeCount = noticeCount
                    })
                    this.$ws.on('clear_notice', async (data) => {
                        let noticeCount = await getNoticeCount()
                        this.noticeCount = noticeCount
                    })
                }
            }
        },
        computed: {
            appId() {
                return this.$route.params.appId;
            },
            groupId() {
                return this.$route.params.groupId;
            },
            worksheetId() {
                return this.$route.params.worksheetId;
            },
            tableMenuExtend() {
                return this.$store.state.tableMenuExtend
            },
            appAuths() {
                let appAuths = this.$store.state.appAuths
                let newAppAuths = {
                    auth:{},
                    isFormAuth: appAuths.isFormAuth
                }
                if(!appAuths || !appAuths?.appAuth){
                    return newAppAuths
                }
                if(this.worksheetId !== undefined){
                    if(!appAuths.isFormAuth){
                        newAppAuths.auth = appAuths.appAuth
                    }
                    else {
                        newAppAuths.auth = appAuths.formAuth[this.worksheetId] || {}
                        newAppAuths.auth["FORM_ADD"] = appAuths.appAuth.FORM_ADD ? true : false
                    }
                }
                return newAppAuths
            },
            count(){
                let count = 0;
                this.noticeCount.forEach(n => {
                    count += n.notice_total
                })
                return count
            }
        }
    }
</script>
<style scoped lang="less">
.applicationContainer{
    width: 100%;
    height: 100%;
}
.header-title{
    margin-right: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 180px;
}
.cgs-icon{
    width: 20px;
    height: 20px
}
.header-menu-item{
    color: rgba(255, 255, 255, 0.8);
    padding: 0 10px 0 20px;
    margin: 0 1px;
    line-height: 30px;
    border-radius: 4px 4px 0 0;
    background-color: rgba(0, 0, 0, 0.1);
}

</style>
<style lang="less">
    @import "../../assets/style/application.less";
    .theme1{
        .applicationTheme(rgba(255, 185, 0,1), rgba(255, 185, 0,0.2))
    }
    .theme2{
        .applicationTheme(rgba(255, 140, 0,1), rgba(255, 140, 0,0.2))
    }
    .theme3{
        .applicationTheme(rgba(247, 99, 12,1), rgba(247, 99, 12,0.2))
    }
    .theme4{
        .applicationTheme(rgba(202, 80, 16,1), rgba(202, 80, 16,0.2))
    }
    .theme5{
        .applicationTheme(rgba(218, 59, 1,1), rgba(218, 59, 1,0.2))
    }
    .theme6{
        .applicationTheme(rgba(239, 105, 80,1), rgba(239, 105, 80,0.2))
    }
    .theme7{
        .applicationTheme(rgba(209, 52, 56,1), rgba(209, 52, 56,0.2))
    }
    .theme8{
        .applicationTheme(rgba(255, 67, 67,1), rgba(255, 67, 67,0.2))
    }

    .theme9{
        .applicationTheme(rgba(231, 72, 86, 1), rgba(231, 72, 86, 0.2))
    }
    .theme10{
        .applicationTheme(rgba(232, 17, 35, 1), rgba(232, 17, 35, 0.2))
    }
    .theme11{
        .applicationTheme(rgba(234, 0, 94, 1), rgba(234, 0, 94, 0.2))
    }
    .theme12{
        .applicationTheme(rgba(195, 0, 82, 1), rgba(195, 0, 82, 0.2))
    }
    .theme13{
        .applicationTheme(rgba(227, 0, 140, 1), rgba(227, 0, 140, 0.2))
    }
    .theme14{
        .applicationTheme(rgba(191, 0, 119, 1), rgba(191, 0, 119, 0.2))
    }
    .theme15{
        .applicationTheme(rgba(194, 57, 179, 1), rgba(194, 57, 179, 0.2))
    }
    .theme16{
        .applicationTheme(rgba(154, 0, 137, 1), rgba(154, 0, 137, 0.2))
    }



    .theme17{
        .applicationTheme(rgba(0, 120, 215, 1), rgba(0, 120, 215, 0.2))
    }
    .theme18{
        .applicationTheme(rgba(0, 99, 177, 1), rgba(0, 99, 177, 0.2))
    }
    .theme19{
        .applicationTheme(rgba(142, 140, 216, 1), rgba(142, 140, 216, 0.2))
    }
    .theme20{
        .applicationTheme(rgba(107, 105, 214, 1), rgba(107, 105, 214, 0.2))
    }
    .theme21{
        .applicationTheme(rgba(135, 100, 184, 1), rgba(135, 100, 184, 0.2))
    }
    .theme22{
        .applicationTheme(rgba(116, 77, 169, 1), rgba(116, 77, 169, 0.2))
    }
    .theme23{
        .applicationTheme(rgba(177, 70, 194, 1), rgba(177, 70, 194, 0.2))
    }
    .theme24{
        .applicationTheme(rgba(136, 23, 152, 1), rgba(136, 23, 152, 0.2))
    }

    .defaultTheme{
        .applicationTheme(rgba(0, 153, 188, 1), rgba(0, 153, 188, 0.2))
    }
    .theme26{
        .applicationTheme(rgba(45, 125, 154, 1), rgba(45, 125, 154, 0.2))
    }
    .theme27{
        .applicationTheme(rgba(0, 183, 195, 1), rgba(0, 183, 195, 0.2))
    }
    .theme28{
        .applicationTheme(rgba(3, 131, 135, 1), rgba(3, 131, 135, 0.2))
    }
    .theme29{
        .applicationTheme(rgba(0, 178, 148, 1), rgba(0, 178, 148, 0.2))
    }
    .theme30{
        .applicationTheme(rgba(1, 133, 116, 1), rgba(1, 133, 116, 0.2))
    }
    .theme31{
        .applicationTheme(rgba(0, 204, 106, 1), rgba(0, 204, 106, 0.2))
    }
    .theme32{
        .applicationTheme(rgba(16, 137, 62, 1), rgba(16, 137, 62, 0.2))
    }

    .theme33{
        .applicationTheme(rgba(122, 117, 116, 1), rgba(122, 117, 116, 0.2))
    }
    .theme34{
        .applicationTheme(rgba(93, 90, 88, 1), rgba(93, 90, 88, 0.2))
    }
    .theme35{
        .applicationTheme(rgba(104, 118, 138, 1), rgba(104, 118, 138, 0.2))
    }
    .theme36{
        .applicationTheme(rgba(81, 92, 107, 1), rgba(81, 92, 107, 0.2))
    }
    .theme37{
        .applicationTheme(rgba(86, 124, 115, 1), rgba(86, 124, 115, 0.2))
    }
    .theme38{
        .applicationTheme(rgba(72, 104, 96, 1), rgba(72, 104, 96, 0.2))
    }
    .theme39{
        .applicationTheme(rgba(73, 130, 5, 1), rgba(73, 130, 5, 0.2))
    }
    .theme40{
        .applicationTheme(rgba(16, 124, 16, 1), rgba(16, 124, 16, 0.2))
    }

    .theme41{
        .applicationTheme(rgba(118, 118, 118, 1), rgba(118, 118, 118, 0.2))
    }
    .theme42{
        .applicationTheme(rgba(76, 74, 72, 1), rgba(76, 74, 72, 0.2))
    }
    .theme43{
        .applicationTheme(rgba(105, 121, 126, 1), rgba(105, 121, 126, 0.2))
    }
    .theme44{
        .applicationTheme(rgba(74, 84, 89, 1), rgba(74, 84, 89, 0.2))
    }
    .theme45{
        .applicationTheme(rgba(100, 124, 100, 1), rgba(100, 124, 100, 0.2))
    }
    .theme46{
        .applicationTheme(rgba(82, 94, 84, 1), rgba(82, 94, 84, 0.2))
    }
    .theme47{
        .applicationTheme(rgba(132, 117, 69, 1), rgba(132, 117, 69, 0.2))
    }
    .theme48{
        .applicationTheme(rgba(126, 115, 95, 1), rgba(126, 115, 95, 0.2))
    }
</style>
